(function (angular) {
    'use strict';

    angular.module('ytong.services').factory('usersManager',usersManager);

    function usersManager(proxyService, growl, Constants, $log){

        var users = [];

        function loadUsers(){
            proxyService.get(Constants.URLS.LOGIN_URL)
                .then(function(responseData){
                    $log.info("Users retrieved successfully.");
                    users = responseData.users;
                }, function(responseData){
                    if(responseData.query_result == Constants.QUERY_RESULTS.NO_RESULTS){
                        users = [];
                        $log.info("No users.");
                    }else {
                        $log.info("Failed retrieving users  from server: " + responseData.log_error);
                        growl.error("Failed retrieving users");
                        users = [];
                    }
                });
        };

        function getUsers(){
            return users;
        }

        function getUsername(userID){
            for(var i=0; i< users.length; i++){
                if(users[i].id === userID){
                    return users[i].username;
                }
            };
        };

        function updateUser(updateUser){

            var user = {};
            user.user = updateUser;

            proxyService.updateEntity(Constants.URLS.LOGIN_URL,user)
                .then(function(){
                    growl.success("User updated");
                    loadUsers();
                }, function() {
                    growl.error("User updating failed");
                });
        };

        function deleteUser(deleteUser){

            var user = {};
            user.user = deleteUser;

            proxyService.deleteEntity(Constants.URLS.LOGIN_URL,user)
                .then(function(){
                    growl.success("User deleted");
                    loadUsers();
                }, function(){
                    growl.error("User deleting failed");
                });
        };

        //interface
        return{
            loadUsers: loadUsers,
            getUsers: getUsers,
            updateUser: updateUser,
            deleteUser: deleteUser,
            getUsername: getUsername
        }
    };


}(angular));